package com.goldsprite.gameframeworks.ecs.component;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;

import java.util.Random;

import com.goldsprite.gameframeworks.ecs.system.*;

public class FollowCamComponent extends Component {
	private TransformComponent target;
	private float camBreatheRange = 15;
	private float breatheTimeScale = 1;//呼吸时长
	private Random breatheRand = new Random();
	private float[] camZoomRect;

	public void setCamZoomRect(float [] camZoomRect) {
		this.camZoomRect = camZoomRect;
	}

	@Override
	public void update(float delta) {
		followCamera(delta);
	}

	float camBreatheXVal = 0;
	private void followCamera(float delta) {
		//跟随相机
		OrthographicCamera cam = GameSystem.worldCamera;
		Vector3 camPos = cam.position;
//		camPos.x = transform.getPosition().x;
//		camPos.y = transform.getPosition().y;
		float followOffsetY = 150/*125*/;//y偏移
		float mul = 3f;
		float interpolation = delta * mul;
		interpolation = 1;//取消插值过渡

		//相机呼吸
		float totalGameDelta = GameSystem.getTotalDeltaTime() * breatheTimeScale;
		float curve = (float) Math.sin(totalGameDelta) * 0.5f;
		float camBreatheYVal = curve * camBreatheRange;
		float interval = 3;//X呼吸间隔
		if (totalGameDelta % interval < 0.1f) {
			float breatheXRangeMin = 0.3f;
			float breatheXDegree = breatheXRangeMin + breatheRand.nextFloat() * (1 - breatheXRangeMin);
			camBreatheXVal = breatheXDegree * camBreatheRange;
			camBreatheXVal -= camBreatheXVal/2f;
		}
		camBreatheYVal = camBreatheXVal = 0;//禁用呼吸

		//插值跟随
		camPos.x = MathUtils.lerp(camPos.x, getTarget().getPosition().x + camBreatheXVal, interpolation);
		camPos.y = MathUtils.lerp(camPos.y, getTarget().getPosition().y + followOffsetY * cam.zoom + camBreatheYVal, interpolation);

		//限制相机左宽度
		camPos.x = Math.max(camPos.x, camZoomRect[0]- (followOffsetY-50) / cam.zoom);
		//限制相机右宽度
		camPos.x = Math.min(camPos.x, camZoomRect[1] + (followOffsetY-50) / cam.zoom);
		//限制相机最低高度
		camPos.y = Math.max(camPos.y, camZoomRect[2] * cam.zoom);
		//限制相机最高高度
		camPos.y = Math.min(camPos.y, camZoomRect[3]);

		GameSystem.worldCamera.update();
	}

	public TransformComponent getTarget() {
		return this.target == null ? fields.transform : this.target;
	}

	public void setTarget(TransformComponent target) {
		this.target = target;
	}
}
